import defaultSettings from '@/settings.js'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: defaultSettings.BASE_RUL,
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    config.headers['Accept-Language'] = store.getters.language

    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code === 200) {
      return res;
    } else {
      if (res.code < 0) {
        MessageBox.confirm(res.msg || this.$t('text.unknownException'), {
          confirmButtonText: this.$t('el.messagebox.confirm'),
          showCancelButton: false,
          closeOnClickModal: false,
          showClose: false,
          type: 'error'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.code > 100) {
        Message({
          message: res.message || res.msg || this.$t('text.unknownException'),
          type: 'error',
          duration: 3 * 1000,
          // showClose:true
        })

        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm(res.mag, {
            confirmButtonText: this.$t('el.messagebox.confirm'),
            cancelButtonText: this.$t('el.messagebox.cancel'),
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
      }
      return Promise.reject(new Error(res.message || res.msg || this.$t('text.unknownException')))
    }
  },
  error => {
    console.log('err' + error) // for debug
    var msgStr = error.message;
    if (error.message.indexOf('timeout') !== -1) {
      msgStr = this.$t('text.serveIsBusy');
    }
    Message({
      message: msgStr,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
